package com.future.lock.me.order;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.future.lock.R;
import com.future.lock.common.MyApp;
import com.future.lock.common.http.HttpUtils;
import com.future.lock.mall.entity.beans.PayInfo;
import com.future.lock.mall.entity.response.BaseDataResponse;
import com.future.lock.mall.tasks.SetOrderStatusTask;
import com.future.lock.mall.utils.Utils;
import com.future.lock.mall.widgets.NoticePopupDialog;
import com.future.lock.me.order.entity.bean.OrderDetailsBean;
import com.future.lock.me.order.entity.bean.OrderListInfoBean;
import com.future.lock.me.order.entity.response.OrderDetailsInfoResponse;
import com.future.lock.pay.PayActivity;
import com.yzh.modaldialog.dialog.impl.SelectorDialog;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.future.lock.me.order.entity.bean.OrderDetailsBean.TYPE_TRAIL;
import static com.future.lock.me.order.entity.bean.OrderListInfoBean.ORDER_STATUS_WAIT_FOR_DELIVERY;

public class OrderDetailsActivity extends PayActivity {

    public static final String ORDER_ID = "order_id";

    @BindView(R.id.statusImageView)
    ImageView statusImageView;

    @BindView(R.id.statusTextView)
    TextView statusTextView;

    @BindView(R.id.diliveryStatusLayout)
    View diliveryStatusLayout;

    @BindView(R.id.diliveryStatus)
    TextView diliveryStatus;

    @BindView(R.id.diliveryCoTextView)
    TextView diliveryCoTextView;

    @BindView(R.id.diliveryNumTextView)
    TextView diliveryNumTextView;

    @BindView(R.id.diliveryStatusLayoutSeperator)
    View diliveryStatusLayoutSeperator;

    @BindView(R.id.userTextView)
    TextView userTextView;

    @BindView(R.id.mobileTextView)
    TextView mobileTextView;

    @BindView(R.id.addressTextView)
    TextView addressTextView;

    @BindView(R.id.icon)
    ImageView icon;

    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.needInstall)
    TextView needInstall;

    @BindView(R.id.installStatus)
    TextView installStatus;

    @BindView(R.id.feeCaption)
    TextView feeCaption;

    @BindView(R.id.feeTextView)
    TextView feeTextView;

    @BindView(R.id.installFeelayout)
    View installFeelayout;

    @BindView(R.id.installFeeTextView)
    TextView installFeeTextView;

    @BindView(R.id.discountLayout)
    View discountLayout;

    @BindView(R.id.discountCaption)
    TextView discountCaption;

    @BindView(R.id.discountTextView)
    TextView discountTextView;

    @BindView(R.id.addFeeLayout)
    View addFeeLayout;

    @BindView(R.id.actualFeeLayou)
    View actualFeeLayou;

    @BindView(R.id.addFeeTextView)
    TextView addFeeTextView;

    @BindView(R.id.actualFeeTextView)
    TextView actualFeeTextView;

    @BindView(R.id.orderNum)
    TextView orderNum;

    @BindView(R.id.cancelButton)
    TextView cancelButton;

    @BindView(R.id.payType)
    TextView payType;

    @BindView(R.id.payTime)
    TextView payTime;

    @BindView(R.id.diliveriedTime)
    TextView diliveriedTime;

    @BindView(R.id.diliveriedTimeCaption)
    TextView diliveriedTimeCaption;

    @BindView(R.id.addFeeAgreePolicyLayout)
    View addFeeAgreePolicyLayout;

    @BindView(R.id.refundPolicyLayout)
    View refundPolicyLayout;

    @BindView(R.id.bottomLayout)
    View bottomLayout;

    @BindView(R.id.priceLayout)
    View priceLayout;

    @BindView(R.id.price)
    TextView price;

    @BindView(R.id.addFeePolicy)
    TextView addFeePolicy;

    @BindView(R.id.operateButton)
    CheckedTextView operateButton;

    @BindView(R.id.refundStatusTextView)
    TextView refundStatusTextView;

    String orderId = "";

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_order_details);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {
        setTitle("订单详情");
        setTitleRight("客服", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLoadingDialog();
                HttpUtils.getHttpApi()
                        .getKefudianhua()
                        .enqueue(new Callback<String>() {
                            @Override
                            public void onResponse(Call<String> call, Response<String> response) {
                                try {
                                    dissmissLoadingDialog();
                                    final String phone = new JSONObject(response.body()).optString("data");
                                    if (!TextUtils.isEmpty(phone)) {
                                        tryToCallKefu(phone);
                                    }
                                }
                                catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFailure(Call<String> call, Throwable t) {
                                dissmissLoadingDialog();
                                toast("获取客服电话失败, 请稍后重试!");
                            }
                        });
            }
        });
        Callback<String> callback = new Callback<String>() {

            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                dissmissLoadingDialog();
                OrderDetailsInfoResponse orderDetailsBean = new OrderDetailsInfoResponse();
                orderDetailsBean.parse(response.body());
                if (orderDetailsBean.success == 1) {
                    setupUisByOrderDetailsBean(orderDetailsBean.data);
                }
                else {
                    toast(orderDetailsBean.msg);
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                dissmissLoadingDialog();
                toast(t.getMessage());
            }
        };

        showLoadingDialog();
        HttpUtils.getHttpApi()
                .getOrderInfo(MyApp.getUserToken(), this.orderId + "")
                .enqueue(callback);
    }

    /**
     * 给客服电话
     *
     * @param phone
     */
    private void tryToCallKefu(String phone) {
        if (Build.VERSION.SDK_INT < 23) {
            Utils.callPhones(OrderDetailsActivity.this, phone);
            return;
        }

        if (ActivityCompat.checkSelfPermission(OrderDetailsActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(OrderDetailsActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 1001);
        }
        else {
            Utils.callPhones(OrderDetailsActivity.this, phone);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1001) {
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    toast("程序需要拨打电话权限才能给客服打电话!");
                }
            }
        }
    }

    private void setupUisByOrderDetailsBean(final OrderDetailsBean data) {
        if (data != null && this.statusImageView != null) {
            this.statusImageView.setImageLevel(data.getStatus());
            this.statusTextView.setText(data.getStatusStr());
            this.userTextView.setText(data.getConsignee());
            this.mobileTextView.setText(data.getPhone());
            this.addressTextView.setText(data.getFullAddress());
            this.title.setText(data.getGoods_name());

            final boolean showRefundStatus = data.needShowRefundStatus();
            this.refundStatusTextView.setVisibility(showRefundStatus ? View.VISIBLE : View.GONE);
            this.refundStatusTextView.setText(data.getRefundStatusStr());

            final boolean isInDelivery = data.showDeliveryStatus();
            this.diliveryStatusLayout.setVisibility(isInDelivery ? View.VISIBLE : View.GONE);
            this.diliveryStatusLayoutSeperator.setVisibility(isInDelivery ? View.VISIBLE : View.GONE);
            if (isInDelivery) {
                this.diliveryStatus.setText(data.getStatus() == ORDER_STATUS_WAIT_FOR_DELIVERY ? "快递小哥正在为您飞奔送货中..." : "快递小哥已为您完成配送");
                this.diliveryCoTextView.setText(data.getExpress_name());
                this.diliveryNumTextView.setText(data.getExpress_no());
            }

            // 商品金额
            final boolean isTrail = data.getType() == TYPE_TRAIL;
            //            this.feeCaption.setText(!isTrail ? "商品全额" : "商品试用押金");
            this.feeTextView.setText(getPriceStr(data.getGoods_price()));

            // 是否有安装费
            final boolean needInstall = data.isIs_install();
            this.installStatus.setText(needInstall ? "需要上门安装" : "无需上门安装");
            this.installFeelayout.setVisibility(needInstall && data.getInstall_fee() > 0 ? View.VISIBLE : View.GONE);
            if (needInstall) {
                this.installFeeTextView.setText("+" + getPriceStr(data.getInstall_fee()));
            }

            // 是否有增值费
            final boolean hasAddedFee = data.isAddedType();
            this.addFeeLayout.setVisibility(hasAddedFee ? View.VISIBLE : View.GONE);
            this.addFeeTextView.setText("+" + getPriceStr(data.getAdded_fee()));

            // 是否有分享立减
            final boolean hasDiscount = data.getDiscount_amount() > 0f;
            this.discountLayout.setVisibility(hasDiscount ? View.VISIBLE : View.GONE);
            if (hasDiscount) {
                this.discountTextView.setText("-" + getPriceStr(data.getDiscount_amount()));
            }

            // 是否显示实付款
            this.actualFeeLayou.setVisibility(data.isPaied() ? View.VISIBLE : View.GONE);
            this.actualFeeTextView.setText(getPriceStr(data.getOrder_amount()));

            // 订单号等等
            this.orderNum.setText(data.getOrder_sn());
            this.payType.setText(data.getPay_type() == 0 ? "支付宝支付" : "微信支付");
            this.payTime.setText(data.getCreate_time());

            final boolean isDeliveried = data.getStatus() == OrderListInfoBean.ORDER_STATUS_FINISHED;
            this.diliveriedTimeCaption.setVisibility(isDeliveried ? View.VISIBLE : View.GONE);
            this.diliveriedTime.setVisibility(isDeliveried ? View.VISIBLE : View.GONE);
            if (isDeliveried) {
                this.diliveriedTime.setText(data.getUpdate_time());
            }

            this.addFeeAgreePolicyLayout.setVisibility(data.showAddedFeeAgreeTips() ? View.VISIBLE : View.GONE);
            this.refundPolicyLayout.setVisibility(data.showRefundPolicyTips() ? View.VISIBLE : View.GONE);

            // 底部操作栏
            this.bottomLayout.setVisibility(data.showBottomLayout() ? View.VISIBLE : View.GONE);
            this.priceLayout.setVisibility(data.showPriceLayout() ? View.VISIBLE : View.GONE);
            this.price.setText(getPriceStr(data.getOrder_amount()));
            this.addFeePolicy.setVisibility(data.showAddedFeePolicyInPriceArea() ? View.VISIBLE : View.GONE);
            this.operateButton.setVisibility(data.showOperateButton() ? View.VISIBLE : View.GONE);
            this.operateButton.setChecked(data.getStatus() == OrderListInfoBean.ORDER_STATUS_WAIT_TO_PAY);
            this.operateButton.setText(data.getOperateButtonCaptionStr());
            this.operateButton.setOnClickListener(view -> {
                if (data.isWaitToPay()) {
                    tryToPayOrder(data.getOrder_id());
                }
                else if (data.isRefundable()) {
                    tryToRefund(data.getOrder_id());
                }
                else if (data.isWaitForDelivery()) {
                    tryToConfirmDelivery(data.getOrder_id());
                }
            });

            // 显示取消按钮
            this.cancelButton.setVisibility(data.isWaitToPay() ? View.VISIBLE : View.GONE);
            this.cancelButton.setOnClickListener(view -> {
                tryToCancel(data.getOrder_id());
            });

            Glide.with(this)
                    .load(data.getHead_img())
                    .placeholder(R.drawable.ssdk_oks_classic_telegram)
                    .dontAnimate()
                    .into(icon);
        }
    }

    private void tryToConfirmDelivery(String order_id) {
        final int choice = new SelectorDialog(this, R.layout.dialog_default) {
            @Override
            protected void onDialogCreate(Dialog dialog, Bundle savedInstanceState) {
                setGravity(Gravity.CENTER);
                super.onDialogCreate(dialog, savedInstanceState);
                ((TextView) dialog.findViewById(R.id.tv_message)).setText("确认已经收到货了吗？");
                ((TextView) dialog.findViewById(R.id.btn_cancel)).setText("取消");
                ((TextView) dialog.findViewById(R.id.btn_ok)).setText("确认");
            }
        }.doModal();

        if (choice == R.id.btn_ok) {
            SetOrderStatusTask.setOrderStatus(MyApp.getUserToken(), order_id, SetOrderStatusTask.STATUS_CONFIRMED, () -> {
                toast("成功确认收货!");
                initView();
            }, () -> toast("确认收货失败, 请稍后再试!"));
        }
    }

    private void tryToRefund(String order_id) {
        showLoadingDialog();
        HttpUtils.getHttpApi()
                .getRefundInfo()
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        try {
                            dissmissLoadingDialog();
                            final String content = new JSONObject(response.body()).optString("data");
                            NoticePopupDialog dialog = new NoticePopupDialog(OrderDetailsActivity.this);
                            dialog.setTitle("退款规则");
                            dialog.setContent(Html.fromHtml(content));
                            dialog.setConfirm("退款");
                            dialog.setCancel("取消");
                            if (dialog.doModal() == AlertDialog.BUTTON_NEGATIVE) {
                                SetOrderStatusTask.setOrderStatus(MyApp.getUserToken(), order_id, SetOrderStatusTask.STATUS_REFUND, () -> {
                                    toast("成功申请退款!");
                                    initView();
                                }, () -> toast("申请退款失败, 请稍后再试!"));
                            }
                        }
                        catch (JSONException e) {
                            e.printStackTrace();
                            toast("获取退款规则说明失败, 请稍后再试!");
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        dissmissLoadingDialog();
                        toast("获取退款规则说明失败, 请稍后再试!");
                    }
                });
    }

    private void tryToCancel(final String orderId) {
        final int choice = new SelectorDialog(this, R.layout.dialog_default) {
            @Override
            protected void onDialogCreate(Dialog dialog, Bundle savedInstanceState) {
                setGravity(Gravity.CENTER);
                super.onDialogCreate(dialog, savedInstanceState);
                ((TextView) dialog.findViewById(R.id.tv_message)).setText("确定取消该订单吗?");
                ((TextView) dialog.findViewById(R.id.btn_cancel)).setText("确定取消");
                ((TextView) dialog.findViewById(R.id.btn_ok)).setText("暂不取消");
            }
        }.doModal();

        if (choice == R.id.btn_cancel) {
            SetOrderStatusTask.setOrderStatus(MyApp.getUserToken(), orderId, SetOrderStatusTask.STATUS_CANCEL, () -> {
                toast("成功取消订单!");
                initView();
            }, () -> toast("取消失败, 请稍后再试!"));
        }
    }

    private void tryToPayOrder(String order_id) {
        showLoadingDialog();
        HttpUtils.getHttpApi()
                .getPayInfo(MyApp.getUserToken(), order_id)
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        dissmissLoadingDialog();
                        BaseDataResponse<PayInfo> response1 = new BaseDataResponse<PayInfo>(PayInfo.class);
                        response1.parse(response.body());
                        if (response1.data != null) {
                            if (response1.data.getPay_type() == 0) {
                                payAli(response1.data.getAlipay_info()
                                                .getTotal_amount(),
                                        response1.data.getAlipay_info()
                                                .getSubject(),
                                        response1.data.getAlipay_info()
                                                .getOrder_sn());
                            }
                            else {
                                payWechat(response1.data.getWxPayJson());
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        dissmissLoadingDialog();
                        toast("获取订单支付信息失败, 请稍后再试!");
                    }
                });
    }

    @OnClick({R.id.addFeeAgreePolicyLayout, R.id.addFeePolicy})
    protected void addFeeInfoClicked() {
        showLoadingDialog();
        HttpUtils.getHttpApi()
                .getZengzhifuwu()
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        try {
                            dissmissLoadingDialog();
                            final String content = new JSONObject(response.body()).optString("data");
                            NoticePopupDialog dialog = new NoticePopupDialog(OrderDetailsActivity.this);
                            dialog.setTitle("增值服务说明");
                            dialog.setContent(Html.fromHtml(content));
                            dialog.setConfirm("知道了");
                            dialog.doModal();
                        }
                        catch (JSONException e) {
                            e.printStackTrace();
                            toast("获取增值服务说明失败, 请稍后再试!");
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        dissmissLoadingDialog();
                        toast("获取增值服务说明失败, 请稍后再试!");
                    }
                });


    }


    static String getPriceStr(float val) {
        return String.format("¥%.2f", val);
    }

    @Override
    protected void initLogic() {

    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        this.orderId = extras != null ? extras.getString(OrderDetailsActivity.ORDER_ID) : this.orderId;
    }

    @Override
    public void paySuccess() {
        toast("支付成功!");
        initView();
    }

    @Override
    public void payFail() {
        toast("支付失败或取消!");
    }
}
